<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">商品管理</text>
      <view class="action-buttons">
        <text class="add-btn" @click="navigateTo('add')">+ 新增商品</text>
        <text class="category-btn" @click="navigateTo('category')">分类管理</text>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-bar">
      <uni-search-bar placeholder="搜索商品名称" @confirm="handleSearch" />
      <view class="filter-tabs">
        <text class="tab-item" :class="{ active: currentFilter === 'all' }" @click="switchFilter('all')">全部</text>
        <text class="tab-item" :class="{ active: currentFilter === 1 }" @click="switchFilter(1)">上架中</text>
        <text class="tab-item" :class="{ active: currentFilter === 0 }" @click="switchFilter(0)">已下架</text>
      </view>
    </view>

    <!-- 商品分类 -->
    <view class="category-container">
      <scroll-view class="category-list" scroll-x>
        <view class="category-item" v-for="(category, index) in categories" :key="index"
          :class="{ active: currentCategory === category.id }" @click="selectCategory(category.id)">
          <text class="category-name">{{ category.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="goods-item" v-for="(item, index) in filteredGoods" :key="index">
        <checkbox class="goods-checkbox" :checked="selectedGoods.includes(item)" @click="toggleGoodsSelection(item)" />
        <image class="goods-image" :src="item.image" mode="aspectFill"></image>
        <view class="goods-info">
          <text class="goods-name">{{ item.name }}</text>
          <text class="goods-price">¥{{ item.price }}</text>
          <text class="goods-sales">月售{{ item.sales }}+</text>
        </view>
        <view class="goods-actions">
          <switch :checked="item.status === 1" @change="toggleGoodsStatus(item)" color="#FF7F50" />
          <view class="edit-btn" @click="navigateTo('edit', item)">
            <uni-icons type="compose" size="20" color="#666"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 批量操作工具栏 -->
    <view class="batch-toolbar" v-if="selectedGoods.length > 0">
      <text class="selected-count">已选{{ selectedGoods.length }}件</text>
      <view class="batch-actions">
        <text class="batch-btn" @click="batchUpdateStatus(1)">上架</text>
        <text class="batch-btn" @click="batchUpdateStatus(0)">下架</text>
        <text class="batch-btn delete" @click="batchDelete">删除</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import {getMerchantId} from '@/utils/merchant.js';
import { getGoodsCategories} from '@/api/goodsCategory';
import { batchUpdateGoodsStatus, batchDeleteGoods, getGoodsList } from '@/api/goods';

const currentFilter = ref('all');
const currentCategory = ref(0);
const searchKeyword = ref('');
const categories = ref([]);
const goodsList = ref([]);
const selectedGoods = ref([]);
const merchantId = ref(0);

const filteredGoods = computed(() => {
  let result = goodsList.value;
  
  // 按分类筛选
  if (currentCategory.value !== 0) {
    result = result.filter(item => item.categoryId === currentCategory.value);
  }
  
  // 按状态筛选
  if (currentFilter.value !== 'all') {
    result = result.filter(item => item.status === (currentFilter.value === 1 ? 1 : 0));
  }
  
  // 按搜索关键词筛选
  if (searchKeyword.value) {
    result = result.filter(item => item.name.includes(searchKeyword.value));
  }
  
  return result;
});

const switchFilter = (filter) => {
  currentFilter.value = filter;
};

const selectCategory = (categoryId) => {
  currentCategory.value = categoryId;
};

const handleSearch = (e) => {
  searchKeyword.value = e.value;
};

const toggleGoodsStatus = (item) => {
  const newStatus = item.status === 1 ? 0 : 1;
  batchUpdateGoodsStatus([item.id], newStatus).then(() => {
    item.status = newStatus;
    uni.showToast({ title: '操作成功', icon: 'success' });
  });
};

const toggleGoodsSelection = (item) => {
  console.log('toggleGoodsSelection', selectedGoods.value);
  const index = selectedGoods.value.findIndex(selected => selected.id === item.id);
  if (index === -1) {
    selectedGoods.value.push(item);
  } else {
    selectedGoods.value.splice(index, 1);
  }
  console.log('endddd', selectedGoods.value);
};

const batchUpdateStatus = (status) => {
  const ids = selectedGoods.value.map(item => item.id);
  batchUpdateGoodsStatus(ids, status).then(() => {
    selectedGoods.value.forEach(item => {
      item.status = status;
    });
    selectedGoods.value = [];
    uni.showToast({ title: '批量操作成功', icon: 'success' });
  });
};

const batchDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的${selectedGoods.value.length}件商品吗？`,
    success: (res) => {
      if (res.confirm) {
        const ids = selectedGoods.value.map(item => item.id);
        batchDeleteGoods(ids).then(() => {
          goodsList.value = goodsList.value.filter(
            item => !selectedGoods.value.some(selected => selected.id === item.id)
          );
          uni.showToast({ title: '删除成功', icon: 'success' });
          selectedGoods.value = [];
        });
      }
    }
  });
};

const navigateTo = (type, item) => {
  let url = '/pages/goods/edit';
  if (type === 'add') {
    url = '/pages/goods/edit';
  } else if (type === 'edit' && item) {
    url = `/pages/goods/edit?id=${item.id}`;
  } else if (type === 'category') {
    url = '/pages/goods/category';
  }
  uni.navigateTo({ url });
};

onShow(() => {
  merchantId.value = getMerchantId(); 
  
  // 获取分类列表
  getGoodsCategories(merchantId.value).then(res => {
    categories.value = [{ id: 0, name: '全部' }, ...res.data];
  });
  
  // 获取商品列表
  fetchGoodsList();
});

const fetchGoodsList = () => {
  const params = {
    merchantId: merchantId.value
  };
  if (currentCategory.value !== 0) {
    params.categoryId = currentCategory.value;
  }
  if (currentFilter.value !== 'all') {
    params.status = currentFilter.value;
  }
  getGoodsList(params)
    .then(res => {
      goodsList.value = res.data;
    });
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #ffffff;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.add-btn {
  padding: 10rpx 20rpx;
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  
  &:active {
    transform: scale(0.95);
  }
}

.category-btn {
  padding: 10rpx 20rpx;
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  
  &:active {
    transform: scale(0.95);
  }
}

.search-bar {
  padding: 20rpx;
  background: #ffffff;
}

.filter-tabs {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
}

.tab-item {
  font-size: 28rpx;
  color: #666;
  padding: 10rpx 0;

  &.active {
    color: #ff6b6b;
    font-weight: bold;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 6rpx;
      background: linear-gradient(to right, #ff9a9e, #ff6b6b);
      border-radius: 3rpx;
      box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
    }
  }
}

.category-container {
  display: flex;
  padding: 20rpx;
  background: #ffffff;
}

.category-list {
  flex: 1;
  white-space: nowrap;
}

.category-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background: #f8f8f8;

  &.active {
    background: #fff;
    color: #ff6b6b;
    border: 1px solid #ff6b6b;
    box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.2);
  }
}

.goods-list {
  padding: 20rpx;
}

.goods-item {
  display: flex;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.goods-price {
  font-size: 32rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.goods-sales {
  font-size: 22rpx;
  color: #999;
}

.goods-actions {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}

.edit-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f8f8f8;
}

.batch-toolbar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.selected-count {
  font-size: 28rpx;
  color: #666;
}

.batch-actions {
  display: flex;
  gap: 20rpx;
  margin-right: 50rpx;
}

.batch-btn {
  padding: 10rpx 30rpx;
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  
  &:active {
    transform: scale(0.95);
  }

  &.delete {
    background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  }
}
</style>